package ie.dcu.spca.view.item;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.quietlycoding.android.picker.NumberPicker;
import com.singularsys.jep.Jep;
import com.singularsys.jep.JepException;

import ie.dcu.spca.Main;
import ie.dcu.spca.R;
import ie.dcu.spca.data.BasicDataManager;
import ie.dcu.spca.data.ItemDataManager;
import ie.dcu.spca.data.ItemUserDataManager;
import ie.dcu.spca.data.ProductDataManager;
import ie.dcu.spca.data.UserDataManager;
import ie.dcu.spca.model.bean.Product;
import ie.dcu.spca.view.CRUDDialog;
import ie.dcu.spca.view.Utility;
import ie.dcu.spca.view.product.ProductDetailForm;
import android.app.Activity;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class ItemCRUDDialog extends CRUDDialog {

    private static ProductDataManager productManager;
    private static UserDataManager userManager;
    private static ItemDataManager itemManager;
    private static ItemUserDataManager iuManager;

    private int productId;
    private int billId;
    private double count;
    private String barcode;

    private ProductDetailForm productForm;
    private EditText etCount;
    private Button bCountCalculate;
    private ListView lvUsers;

    public ItemCRUDDialog() {
        productForm = new ProductDetailForm(this);
    }

    @Override
    protected void addOkButtonClickOpt(View v) {
        productId = productManager.existOrCreate(productId, productForm
                .getName(), productForm.getBarcode(), productForm.getPrice(),
                productForm.getCategoryId(), productForm.getUnitId());
        id = itemManager.create(billId, productId, count);
        itemUserUpdate(lvUsers, id);
    }

    private void itemUserUpdate(ListView lv, int itemId) {
        Adapter adapter = lv.getAdapter();
        List<Map<String, Integer>> idWeightList = new LinkedList<Map<String, Integer>>();
        for (int i = 0; i < adapter.getCount(); i++) {
            Map<String, Object> map = (Map<String, Object>) adapter.getItem(i);
            if (map == null)
                continue;
            NumberPicker et = (NumberPicker) lv.getChildAt(i).findViewById(
                    R.id.userCountNP);
            int userId = (Integer) map.get(BasicDataManager.ID);
            int iuCount = et.getCurrent();

            Map<String, Integer> resMap = new HashMap<String, Integer>();
            resMap.put(BasicDataManager.ID, userId);
            resMap.put(BasicDataManager.WEIGHT, iuCount);

            idWeightList.add(resMap);
        }
        iuManager.updateOrCreate(itemId, idWeightList);

    }

    @Override
    protected void bindWidgetOnCreate() {
        productForm.bindWidgetOnCreate();
        etCount = (EditText) findViewById(R.id.countEditText);
        bCountCalculate = (Button) findViewById(R.id.calculateButton);
        bCountCalculate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                expressionParse(etCount.getText().toString(), etCount);
            }
        });
        lvUsers = (ListView) findViewById(R.id.dataListView);

        LayoutInflater inf = LayoutInflater.from(lvUsers.getContext());
        lvUsers.addHeaderView(inf.inflate(R.layout.user_count_setting_view,
                null));

        setUserCountListAdapter(lvUsers, id);

        ((Button) lvUsers.findViewById(R.id.clearButton))
                .setOnClickListener(new UserCountButtonClickListener(lvUsers, 0));
        ((Button) lvUsers.findViewById(R.id.defaultButton))
                .setOnClickListener(new UserCountButtonClickListener(lvUsers, 1));

        productFormInitialize(productId, barcode);
    }

    private boolean expressionParse(String expression, EditText et) {
        Jep jep = new Jep();
        try {
            jep.parse(expression);
            double res = jep.evaluateD();
            et.setText(Double.toString(res));
            return true;
        } catch (JepException e) {
            Toast.makeText(this,
                    this.getString(R.string.error_count_expression),
                    Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private void setUserCountListAdapter(ListView lv, int itemId) {
        List<Map<String, Object>> data = userManager.getIdNameMapList();
        for (Map<String, Object> map : data) {
            map.put(USER_COUNT, iuManager.getCount(itemId, (Integer) map
                    .get(BasicDataManager.ID)));
        }
        lv.setAdapter(getIdNameCountSimpleAdapter(this, data));
        Utility.setListViewHeightBasedOnChildren(lv);
    }

    private static final String USER_COUNT = "userCount";

    public static SimpleAdapter getIdNameCountSimpleAdapter(Activity parent,
            List<Map<String, Object>> data) {
        SimpleAdapter adapter = new SimpleAdapter(parent, data,
                R.layout.user_count_view, new String[] { BasicDataManager.NAME,
                        USER_COUNT }, new int[] { R.id.nameTextView,
                        R.id.userCountNP });
        adapter.setViewBinder(new UserCountViewBuilder());
        return adapter;
    }

    @Override
    protected void deleteBeanOkButtonClickOpt(DialogInterface dialog) {
        itemManager.delete(id);
    }

    @Override
    protected String getDeleteDataConfirmTip() {
        return this.getString(R.string.deleteBillItemConfirmTip)
                + itemManager.getName(itemManager.get(id));
    }

    @Override
    protected int getContentView() {
        return R.layout.billitemcruddia;
    }

    @Override
    protected boolean initializeValuesFromWidget() {
        productForm.initializeValuesFromWidget();
        if (!expressionParse(etCount.getText().toString(), etCount))
            return false;
        count = Double.parseDouble(etCount.getText().toString());
        return true;
    }

    @Override
    protected void setValueFromIntentExtrasOnCreate() {
        productManager = Main.dataManager.productDataManager();
        userManager = Main.dataManager.userDataManager();
        itemManager = Main.dataManager.itemDataManager();
        iuManager = Main.dataManager.itemUserDataManager();

        id = bundle.getInt(BasicDataManager.ID);
        billId = bundle.getInt(BasicDataManager.BILL_ID);
        productId = bundle.getInt(BasicDataManager.PRODUCT_ID);
        barcode = bundle.getString(BasicDataManager.BARCODE);

    }

    private void productFormInitialize(int productId, String barcode) {
        Product product = productManager.get(productId, barcode);
        productForm.updateBeanWidgetInitialize(product);
    }

    @Override
    protected void updateBeanWidgetInitialize() {
        productFormInitialize(productId, barcode);
        count = itemManager.get(id).getCount();
        etCount.setText(Double.toString(count));
    }

    @Override
    protected void updateOkButtonClickOpt(View v) {
        productId = productManager.existOrCreate(productId, productForm
                .getName(), productForm.getBarcode(), productForm.getPrice(),
                productForm.getCategoryId(), productForm.getUnitId());
        itemManager.update(id, billId, productId, count);
        itemUserUpdate(lvUsers, id);
    }

}
